$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/student_adjust_model.php';
    var cboObj;
	var objSelectTable=[];
	
	initialData();
	
	 function initialData(){
		/*$.get(url,{"m":"age_level"} , function(data){
			$("#age_level").html(data);
		});*/
		
		$("#cboClass_Search").append($('<option></option>').val(0).html(''));
		$.get(url, {"m":"class"},function(data){
			cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					
					$("#cboClass_Search").append(
							$('<option></option>').val(text).html(index)
					);
					 
				});
				$("#cboClass_Search").val(1);
			//Load Room from Class (initial)
			LoadRoom(0);	 
			//Load Data Initail
			$("#btnSearch").click();
			}
		});

		 $.get(url, {"m":"year"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboYear_Search").append(
						$('<option></option>').val(text).html(text)
					);
				});
				$.get(url,{"m":"curryear"},function(data){
					$("#cboYear_Search").val(data);
					LoadData('','',1,1,data);
				});
			}
			
		});
	}
	
	$("#cboClass_Search").change(function(){
		var cid=$(this).val();
		
		$("#cboRoom_Search").find('option').remove();	
		LoadRoom(cid);
	
	});	
	
	 function LoadRoom(cid){
	 	$.get(url, {"m":"room","i":cid},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboRoom_Search").append(
						$('<option></option>').val(text).html(index)
					);
				});
			}
		});
	 }
	 function LoadData(co,name,cid,r,year){
		BlockUI();
        $( "#resultData tbody tr" ).remove();
 
		/*$.post(url,{'m':'getRoom_amt','cid':cid},function(data){
			$("#roomInfo").html(data);
		});*/
		if ($("#"));
 
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			 "bPaginate": false,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"cid","value":cid},
								{"name":"r","value":r},
								{"name":"co","value":co},
								{"name":"n","value":name},
								{"name":"year","value":year}
							);
				},
			"aoColumnDefs":[
			{  "bVisible": false , "aTargets": [ 1 ] },	
			{	"bVisible": false , "aTargets": [ 2 ] },	
				{   "bSortable": true, "aTargets": [ 3 ] ,"sClass":"text-left"},	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"left" },	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"left" },
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"center" },	
				{	"bVisible": false , "aTargets": [ 7 ] },	
				{	"bVisible": false , "aTargets": [ 8 ] },	
				{ "aTargets": [ 9 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						var cbo_html="<div class='controls'><select class='span2 m-wrap cbo_class' name='cbclass' style='width:150px !important;'> ";
						cbo_html += "";
						$.each(cboObj, function(index, text) {
							var select = "";
							
							if ((parseInt( full[2]) +1) == parseInt( text))
								select = "selected";
								
							cbo_html += "<option value='"+text+"' "+select+" >"+index+"</option>";
						});
						cbo_html += "</select></div>";
						return cbo_html;
					}
				},
				{"aTargets": [ 10 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						var cbo_html="<div class='controls'><select class='span2 m-wrap cbo_room' name='cbroom' style='width:60px !important;'> ";
						var obj= full[7];
				
						$.each(obj, function(index, text) {
							select="";
							if ( full[8] == index)
								select = "selected";
								
								cbo_html += "<option value='"+text+"' "+select+"  >"+index+"</option>";
							});
							cbo_html += "</select></div>";
							return cbo_html;
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					setTimeout(function(){$.unblockUI();},3500);
				  
				} 
		 } );
		 
      }
	  
	 $(".cbo_class").live('change',function(){
	     var rowSelect=$(this).parent().parent().parent();
		 
		var cbroom = rowSelect.find("select[name=cbroom]");  
		cbroom.find('option').remove();	
		
		var cid= $(this).val();
		if (cid==0){
			cbroom.append($('<option></option>').val(0).html('--'));
		}else{
			$.post(url,{'m':'room','cid':cid},function(data){
				var obj=eval('('+data+')');	
				if (obj != null){
					$.each(obj, function(index, text) {
						cbroom.append(
								$('<option></option>').val(text).html(index)
						);
						 
					});
				}
			});
		}
	 });
	$("#btnCancel").click(function(){
		$('#table_detail').dataTable().fnClearTable();
		objSelectTable=[]
	});
	$("#btnSearch").click(function(){
		var _code = $("#txtCode").val();
		var _name = $("#txtName").val();
		var _cid = $("#cboClass_Search").val();
		var _room = $("#cboRoom_Search").val();
		var _year = $("#cboYear_Search").val();
		LoadData(_code , _name, _cid, _room ,_year);
	});
  
	$("#btnSave").live('click',function(){
		  var main_table= $('#resultData').dataTable();
		  var detail_table=$('#table_detail').dataTable({ 
			"bFilter": false,
			"bDestroy": true,
			"bPaginate": false,
			"bLengthChange": false
			,"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		  });
		  
	   main_table.$('tbody tr').each(function() {
				
				var userData = main_table.fnGetData(this);
				var cbroom = $(this).find("select[name=cbroom]");  
				var cboclass= $(this).find("select[name=cbclass] option:selected").text(); 
				var cboclass_id= $(this).find("select[name=cbclass] option:selected").val(); 
				
				if (cboclass_id!=0){
					objSelectTable.push({'sid':userData[1],'cid':cboclass_id,'r':cbroom.val()});
					detail_table.fnAddData( [
						0,
						userData[1],
						cboclass_id,
						userData[4],
						userData[6],
						cboclass +" / " + cbroom.val(),
						cbroom.val()
					]);
					detail_table.fnSetColumnVis( 1, false );
					detail_table.fnSetColumnVis( 2, false );
					detail_table.fnSetColumnVis( 6, false );
			 
					 
				}
			});
		});		
	
	$("#btnConfirm").click(function(){
		 if (objSelectTable.length>0){
			 
			 $.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'m':'add','list':objSelectTable},
					success: function(data){
						 //LoadData(1);
						 $("#btnSearch").click();
						 $("#popup").modal('hide');
						 
					}
			});
			 
		 }
	});
	
	$("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});	

  
    
});


